package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 用于将消息写入文件
 *
 * @author Administrator
 */
@Component
@Slf4j
public class FileUtil {

    /**
     * 根据参数输出文件
     *
     * @param filePath 文件路径
     * @param data     数据对象
     * @param size     写出的条数
     */
    public static void writeDataToFile(String filePath, LinkedBlockingQueue<String> data, int size) {
        try {
            // 创建 BufferedWriter 对象，提高写入性能
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8));
            // 写入数据
            for (int i = 0; i < size; i++) {
                bufferedWriter.write(data.take());
                if (i < size - 1) {
                    // 写入换行符
                    bufferedWriter.newLine();
                }
            }
            // 关闭资源
            bufferedWriter.close();
            log.info("------writeDataToFile [{}] 条！------", size);
        } catch (IOException | InterruptedException e) {
            log.error("------writeDataToFile Failed [{}]------", e.getMessage());
        }
    }

    public ResponseEntity<byte[]> getImage(String pic) {
        File file = new File(pic);
        byte[] imageBytes = {};
        try {
            imageBytes = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }
}
